import addtablemgtsApi from '../../../common/api/ctn/auditmain.api.js'
import doT from '../../../../vendor/template/doT.js';
import { requestDict, DictionaryType } from '../../../common/dictionary/dictionary-type.js';

let _vm, checkEmploy = [], employeesList = [], checkboxList = [],invtryLocatnInfo={},_personOrg=[],_suppliersList = [], recevEntries = [], saleEntries = [];
const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const addrecevTemplate = doT.template($('#addrecev-template').text());
let auditItemList = JSON.parse(Utils.GetSessionStorage("auditItemList"));
let companyList=[];

(function (window, document, $) {
    $(function () {
        _vm = new Vue({
            el: "#addentryrgst-form",
            data() {
                return {
                    "bizDate": moment(new Date()).format('YYYY-MM-DD'),
                    "scoreDate": moment(new Date()).format('YYYY-MM-DD'),
                    "scorerIds":'',
                    "scorer":'',
                    "company": {
                        "id": '',
                        "name": ''
                    },
                    "department": {
                        "id": '',
                        "name": ''
                    },
                    "remark": '',
                    // "recevEntries": [
                    //     {
                    //         "auditItemId": "",
                    //         "textt": "",
                    //         "text": "",
                    //         "weight": "",
                    //         "prodSafeCategory": '',
                    //         "prodSafeCategoryName": '',
                    //         "inspectProject": '',
                    //         "inspectProjectName": '',
                    //         "deduct": "",
                    //         "reason": "",
                    //         "suggestion": "",
                    //         "principalIds": "",
                    //         "principal": "",
                    //         "timeLimit": "",
                    //         "result": "",
                    //         "resultName": "",
                    //         "imageList": [],
                    //         "image": "",
                    //         "isQualified": false,
                    //         "isRectify": '',
                    //     }
                    // ],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                let ids = Utils.GetSessionStorage("ids")
                if (params.id || ids) {
                    document.title = '管理表 - 编辑'
                    $('#sltrregsDiv').css('display', 'none')
                }
                else {
                    $('#sltrregsDiv').css('display', 'block')
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式

        clickFun();
        _initCommand();
    });
    // 初始化数据
    const _initCommand = async () => {
        // 评分人
        $(`#scorerIds`).select2({
            language: "zh-CN",
            allowClear: true,//允许清空
            placeholder: '请选择人员...', //默认文字提示
            multiple: true, //是否多选
            ajax: {
                url: Utils.CurDomain.EmployeeMgtUrl + `/emplrecds/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        Status: true,
                        // SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1,
                        ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {})
                    };
                },
                cache: true,
                delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
                //minimumInputLength: 1, // 只有当输入长度大于或等于1时，才会触发搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.id = item.id
                        item.text = `${item.name}`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                error: Utils.AjaxError
                //minimumInputLength: 1,
            }
        });
        $('#scorerIds').setSelectValue();
        $(`#scorerIds`).on("select2:select", function (e) {
            let _ids = [], _names = [];
            let list = $(this).select2('data');
            for (let i = 0; i < list.length; i++) {
                _ids.push(list[i]?.id);
                _names.push(list[i]?.text);
            }
            _vm.scorerIds = _ids.join(",");
            _vm.scorer = _names.join(",");
        });

        // 公司
        await addtablemgtsApi.getOrgInfo('ooca', 10).then(res => {
            companyList = res;
            $('#company').select2({
                placeholder: '请选择公司...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: res.map(item => {
                    return {
                        id: item.id,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name,
                        ...item
                    }
                }),
            });
            $('#company').setSelectValue();
        });

        // 选择公司
        $('#company').on('select2:select',async function (e) {
            getdepartment($(this).select2('data')[0]?.id);
            _vm.company.id = $(this).val();
            _vm.company.name = $('#company').select2('data')[0].name;
            let tags = $(this).select2('data')[0]?.tags;
            //获取审查项列表
            await addtablemgtsApi.getAuditItemsList({ tags: tags }).then(res => {
                auditItemList = res.concat([]);
            })
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 选择部门
        $('#department').on('select2:select', function (e) {
            _vm.department.id = $(this).val();
            _vm.department.name = $('#department').select2('data')[0].name;
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 选择业务日期
        $('#search-date').on('click', function () {
            pick();
        });
        // 选择评分日期
        $('#score-date').on('click', function () {
            pickscore();
        });

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            document.title = '入圈登记 - 编辑'
            await addtablemgtsApi.getPenentregs(ids).then(res => {
                res.bizDate = moment(res.bizFormObj.bizDate).format('YYYY-MM-DD')
                res.penEntTime = moment(res.penEntTime).format('YYYY-MM-DD HH:mm')
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.penEntEntry.map(item => {
                    item.seq = Number(item.seq) - 1
                });
                res.recevEntries.map(item => {
                    item.seq = Number(item.seq) - 1;
                    if(item.cfmWeight == 0){
                        item.cfmWeight = '';
                    }
                    if(item.cfmAvgWgh == null){
                        item.cfmAvgWgh = 0;
                    }
                    if(!(item.carWghTkt.id)){
                        item.carWghTkt.netWeight = '';
                    }
                });
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.penEntEntry))
                JSON.stringify(Utils.SetSessionStorage("getReceveEntry", res.recevEntries))
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"));
        if (Utils.IsNotNull(getMainInfo)) {
            var companyName = cutstr(getMainInfo.company.name, 20); // 截取字符串
            const propertiesToCopy = [
                "bizDate","scoreDate","scorerIds","scorer","company","department","remark"
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = getMainInfo[prop];
            }, {});
            $(`#company`).select2('val', getMainInfo.company.id); // 假设您想根据ID设置选中值
            $(`#company`).next('.select2-container').find('.select2-selection__rendered').text(companyName);
            getdepartment(getMainInfo.company.id,getMainInfo.department);
            if (getMainInfo.scorerIds.indexOf(',') == -1) {
                $(`#scorerIds`).setSelectValue(getMainInfo.scorerIds, getMainInfo.scorer)
            } else {
                $(`#scorerIds`).setSelectValue(getMainInfo.scorerIds.split(','), getMainInfo.scorer.split(','));
            }
        }
        
        // 获取分录数据
        let getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
        if (getReceveEntry) {
            $('#recevEntries').empty().append(addrecevTemplate(getReceveEntry));
        }

        // 点击 新增分录
        $('#add-recevEntries').on("click", function (e) {
            // 存储数据
            storeSession();
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            if (_vm.company.id) {
                if(Utils.IsNotNull(auditItemList)){
                    window.sessionStorage.removeItem("auditItemList");
                    // 审查项列表
                    JSON.stringify(Utils.SetSessionStorage("auditItemList", auditItemList))
                    location.href = `../prodsafetymgt/tablemgtentry.html?index=${index}`;
                }else{
                    $.toptip('审查项列表为空', 'warning');
                    return
                }
            }else{
                $.toptip('请先选择公司', 'warning');
                return
            }
        })
        // 点击 编辑分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-edit-recev]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../prodsafetymgt/tablemgtentry.html?index=${index}&isEdit=true`;
        });
        // 点击 删除分录
        $(document).on('click', '#recevEntries div[data-flag=table-click-delete-recev]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            if(!getReceveEntry){
                                getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry"));
                            }
                            let datas = getReceveEntry.filter(item => item.seq != seq)
                            // 重新排序
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getReceveEntry", info))
                            info.forEach(item => {
                                item.isShowEdit = _vm.isShowAddRecev == true?'block':'none';
                                item.isShowSale = _vm.isShowAddRecev == true?'none':'block';
                            })
                            $('#recevEntries').empty().append(addrecevTemplate(info));
                            $.closeModal();
                        }
                    }
                ]
            });
        });

    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    // 保存分录以上的内容
    const storeSession = () => {
        const propertiesToCopy = [
            "bizDate","scoreDate","scorerIds","scorer","company","department","remark"
        ];
        const deliverDatas = propertiesToCopy.reduce((obj, prop) => {
            obj[prop] = _vm[prop];
            return obj;
        }, {});

        Utils.SetRouterState('deliverDatas', deliverDatas)
    }
    
    // 日期选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }
    // 日期选择器
    const pickscore = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.scoreDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }
    // 时间选择器
    function isWhichTime() {
        let years = [];
        let mouth = [];
        let date = [];
        let hours = [];
        let minite = [];
        if (!years.length && !mouth.length) {
            for (let i = 1889; i <= 2030; i++) {
                years.push({
                    label: i + "年",
                    value: i
                });
            }
        }
        if (!mouth.length) {
            mouth = costomDatePicker(mouth, 1, 13, "月")
        }
        if (!date.length) {
            date = costomDatePicker(date, 1, 32, "日")
        }
        if (!hours.length) {
            hours = costomDatePicker(hours, 0, 24, "时")
        }
        if (!minite.length) {
            minite = costomDatePicker(minite, 0, 60, "分")
        }

        weui.picker(years, mouth, date, hours, minite, {
            id: new Date(),//让每一个点击弹框得都有一个不一样得id，这样就避免了共用一个弹框得时候，打开得日期是上一次另外一个得日期回显
            defaultValue: [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds()],
            onConfirm: result => {
                //result 是数组，返回得是当前选中得数，如[{lable:'2019年,value:2019},{lable:'2月,value:2}，{lable:'2号,value:2}]
                if (result.length) {
                    //yyyy-mm-dd hh:mm:ss
                    let time = result[0].value + '-' + result[1].value + '-' + result[2].value + ' ' + result[3].value + ':' + result[4].value;
                    _vm.penEntTime = time
                }
            }
        });
    }

    //自定义日期:月时分秒
    function costomDatePicker(years, startTime, endTime, str) {
        for (let j = startTime; j < endTime; j++) {
            years.push({
                label: ('' + j).length === 1 ? '0' + j + str : '' + j + str,
                value: ('' + j).length === 1 ? '0' + j : '' + j,
            });
        }
        return years;
    };

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            window.sessionStorage.removeItem("auditItemList");
            window.sessionStorage.removeItem("getReceveEntry");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../prodsafetymgt/auditmain.html?v=${Utils.GetTime()}`;
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))
            if (!Utils.IsNotNull(_vm.bizDate)) {
                return $.toptip(`请选择业务日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.scoreDate)) {
                return $.toptip(`请选择评分日期!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.scorer)) {
                return $.toptip(`请选择评分人!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.company)) {
                return $.toptip(`请选择公司!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加分录信息!`, 'warning');
            }
            if (_.uniqBy(entries, item => item.auditItemId).length !== entries.length) {
                return $.toptip(`同种明细只允许存在一条分录信息!`, 'warning');
            }
            
            savetips();
        })
    }
    // 保存 66
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;"><div class="addentry">是否确认保存该单据？</div></div></div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "确定", onClick: function () {
                        $.closeModal();
                        const propertiesToCopy = [
                            "bizDate","scoreDate","scorerIds","scorer","company","department","remark"
                        ];
                        const datas = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        let ids = Utils.GetSessionStorage("ids");
                        let entries = JSON.parse(Utils.GetSessionStorage("getReceveEntry"))||[]; 
                        if(entries.length > 0 ){
                            entries.forEach((item) => {
                                let imageId='';
                                item.imageList.forEach((itm)=>{
                                    imageId += ','+itm.imageId;
                                })
                                item.image = imageId.substring(1, imageId.length);
                                item.text = item.textt;
                            })
                        }
                        
                        // 重新赋值
                        entries.map(item => item.seq = Number(item.seq) + 1);
                        let newItemList = auditItemList.map(item => { return { ...item, auditItemId: item.id } })
                        // 合格项列表
                        let qualifiedrList = _.xorBy(entries, newItemList, 'auditItemId')
                        let lastSeq = entries[entries.length - 1].seq;
                        qualifiedrList = qualifiedrList.map((item, index) => {
                            return {
                                ...item,
                                isQualified: true,
                                seq: +lastSeq + index + 1,
                            }
                        })
                        // 合格项与不合格项合并
                        let endEntires = [...entries, ...qualifiedrList];
                        datas.entires = [...endEntires]
                        if (Utils.IsNotNull(ids)) {
                            addtablemgtsApi.updateAuditTables(ids, datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("auditItemList");
                                    window.sessionStorage.removeItem("getReceveEntry");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./auditmain.html`;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                        else {
                            addtablemgtsApi.setAuditTables(datas).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("auditItemList");
                                    window.sessionStorage.removeItem("getReceveEntry");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `./auditmain.html`;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }
    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    // 获取部门
    const getdepartment = (orgId, json) => {
        $(`#department`).attr('disabled',false);
        addtablemgtsApi.getOrgInfo(orgId, 1).then(res => {
            $(`#department`).empty().select2({
                placeholder: '请选择部门...',//默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            $(`#department`).setSelectValue();
            if (json) {
                let departmentName = cutstr(json.name, 20); // 截取字符串
                $(`#department`).select2('val', json.id); // 假设您想根据ID设置选中值
                $(`#department`).next('.select2-container').find('.select2-selection__rendered').text(departmentName);
    
            }
        });
    }


})(window, document, jQuery)


